/*
 * Copyright 2023-2085 xujin <ceo@itgrail.com>
 *
 * Licensed under the Grail License, Version 1.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * https://itgrail.com/docs?id=3&catalogId=87
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.itgrail.pilot.app.command.query;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.base.Preconditions;
import com.itgrail.pilot.app.command.cmo.OkrPeriodButtonCmd;
import com.itgrail.pilot.app.command.cmo.query.ListUserOKRCmd;
import com.itgrail.pilot.app.command.co.*;
import com.itgrail.pilot.app.converter.*;
import com.itgrail.pilot.domain.user.contant.OkrConstants;
import com.itgrail.pilot.infrastructure.tunnel.db.dao.*;
import com.itgrail.pilot.infrastructure.tunnel.db.dataobject.*;
import com.itgrail.pilot.infrastructure.tunnel.util.SessionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import com.itgrail.grail.cqrs.annotation.CmdHandler;
import com.itgrail.grail.cqrs.command.CommandExecutorI;
import com.itgrail.grail.dto.ResultData;
import com.itgrail.grail.exception.BusinessException;

import java.util.*;
import java.util.stream.Collectors;


@CmdHandler
public class ListUserOKRCmdExe implements CommandExecutorI<ResultData<OkrDetailCO>, ListUserOKRCmd> {

    @Autowired
    private OkrPeriodMapper okrPeriodMapper;

    @Autowired
    private ObjectiveMapper mapper;

    @Autowired
    private KeyResultMapper keyResultMapper;

    @Autowired
    private ObjectiveClientConverter objectiveClientConverter;

    @Autowired
    private KeyResultClientConverter keyResultClientConverter;

    @Autowired
    private OkrPeriodClientConverter okrPeriodClientConverter;

    @Autowired
    private ClassifyMapper classifyMapper;

    @Autowired
    private KeyCommentMapper keyCommentMapper;

    @Autowired
    private AllCommentMapper allCommentMapper;

    @Autowired
    private KeyCommentClientConverter keyCommentClientConverter;

    @Autowired
    private AllCommentClientConverter allCommentClientConverter;

    @Autowired
    private UserOkrAlignMapper userOkrAlignMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PeriodControlMapper periodControlMapper;

    @Autowired
    private DepartmentMapper departmentMapper;


    @Override
    public ResultData execute(ListUserOKRCmd cmd) {
        ResultData resultData = ResultData.success(null);
        check(cmd);
        //查询该周期下  用户的所有okr
        List<Integer> userOkrs = findUserOkrs(cmd);
        List<OkrDetailCO> list = new ArrayList<>();
        boolean leader = isLeader(cmd.getUserId(), cmd.getCurrentUserId());
        if (!CollectionUtils.isEmpty(userOkrs)) {
            userOkrs.forEach(x -> {
                OkrDetailCO detail = findDetail(x);
                //查询对齐的o
                List<OkrAlignDetailCO> userAlignOkrs = getUserAlignOkrs(x);
                detail.setUserAlignOkrs(userAlignOkrs);
                detail.setLeader(leader);
                list.add(detail);
            });
        }
        resultData.setData(list);
        return resultData;
    }

    protected boolean check(ListUserOKRCmd cmd) {
        Preconditions.checkNotNull(cmd, "cmd不能为null");
        Preconditions.checkNotNull(cmd.getOkrPeriodId(), "周期id不能为null");
        Preconditions.checkNotNull(cmd.getUserId(), "userId不能为null");
        return true;
    }


    /**
     * 上级是否能评分的判断逻辑
     * @param userId
     * @param currentUserId
     * @return
     */
    protected boolean isLeader(Integer userId, Integer currentUserId) {
        //查看的人判断当前登陆的人是上级
        UserDO userDO = userMapper.findByUserId(userId);
        //当前登陆的是Leader
        UserDO currentDO = userMapper.findByUserId(currentUserId);
        if (userDO != null && currentDO != null) {
            //查询被查看人的所处的部门
            List<DepartmentDO> departmentUserDOList= departmentMapper.findByUserId(userId);
            return judge(departmentUserDOList,currentUserId);
        }
        return false;
    }

    /**
     * 当前登录人的Id是查看人其中的一个部门Id,则是leader
     * @param checkDepartMentList
     * @param leaderId
     * @return
     */
    Boolean judge(List<DepartmentDO> checkDepartMentList,Integer leaderId){
        if(judgeListIsNotNull(checkDepartMentList)){
            for (DepartmentDO userDepartMent:checkDepartMentList) {
                Integer departMentOwnerId=userDepartMent.getLeaderId();
                if (null!=departMentOwnerId&&leaderId.equals(departMentOwnerId)) {
                    return true;
                }
            }
        }
        return false;
    }

    Boolean judgeListIsNotNull(List<DepartmentDO> list ){
        if (null!=list && !list.isEmpty()) {
            return true;
        }
        return false;
    }

    protected List<OkrAlignDetailCO> getUserAlignOkrs(Integer okrId) {
        List<OkrAlignDetailCO> list = new ArrayList<>();
        QueryWrapper<UserOkrAlignDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("start_objective_id", okrId);
        List<UserOkrAlignDO> alignDOList = userOkrAlignMapper.selectList(queryWrapper);
        Map<Integer, String> userNameId = new HashMap<>();
        if (!CollectionUtils.isEmpty(alignDOList)) {
            //对齐的o
            alignDOList.forEach(x -> {
                OkrAlignDetailCO okrAlignDetailCO = new OkrAlignDetailCO();
                Integer acceptObjectiveId = x.getAcceptObjectiveId();
                OkrDetailCO detail = findDetail(acceptObjectiveId);
                Integer acceptUserId = x.getAcceptUserId();
                QueryWrapper<UserDO> dingUserDOQueryWrapper = new QueryWrapper<>();
                dingUserDOQueryWrapper.eq("user_id", acceptUserId);
                UserDO userDO = userMapper.selectOne(dingUserDOQueryWrapper);
                if (userDO != null) {
                    okrAlignDetailCO.setUserName(userDO.getName());
                    okrAlignDetailCO.setUserId(userDO.getUserId());
                    userNameId.put(userDO.getUserId(), userDO.getName());
                }
                List<OkrDetailCO> userAlignOkrs = new ArrayList<>();
                userAlignOkrs.add(detail);
                okrAlignDetailCO.setUserAlignOkrs(userAlignOkrs);
                list.add(okrAlignDetailCO);
            });
        }
        Map<Integer, List<OkrDetailCO>> map = new HashMap<>();
        list.forEach(x -> {
            if (map.containsKey(x.getUserId())) {
                List<OkrDetailCO> userOkrs = map.get(x.getUserId());
                if (!CollectionUtils.isEmpty(userOkrs)) {
                    userOkrs.addAll(x.getUserAlignOkrs());
                }
            } else {
                map.put(x.getUserId(), x.getUserAlignOkrs());
            }
        });
        List<OkrAlignDetailCO> okrAlignDetailCOS = new ArrayList<>();
        for (Map.Entry<Integer, List<OkrDetailCO>> entry : map.entrySet()) {
            Integer userId = entry.getKey();
            List<OkrDetailCO> value = entry.getValue();
            OkrAlignDetailCO detailCO = new OkrAlignDetailCO();
            detailCO.setUserId(userId);
            detailCO.setUserName(userNameId.get(userId));
            detailCO.setUserAlignOkrs(value);
            okrAlignDetailCOS.add(detailCO);
        }
        return okrAlignDetailCOS;
    }

    /**
     * 封装okr详情
     *
     * @param objectiveId
     * @return
     */
    protected OkrDetailCO findDetail(Integer objectiveId) {
        OkrDetailCO okrDetailCO = new OkrDetailCO();
        //获取目标信息
        ObjectiveDO objectiveDO = mapper.selectById(objectiveId);
        Integer classifyId = objectiveDO.getClassifyId();
        ObjectiveDetailCO objectiveDetailCO = objectiveClientConverter.dataToClient(objectiveDO);
        objectiveDetailCO.setUserScore(objectiveDetailCO.getMyScore());
        if (!StringUtils.isEmpty(objectiveDO.getNotifyUserList())) {
            objectiveDetailCO.setNotifyUsers(JSONArray.parseArray(objectiveDO.getNotifyUserList(), UserCO.class));
        } else {
            objectiveDetailCO.setNotifyUsers(new ArrayList<>());
        }
        ClassifyDO classifyDO = classifyMapper.selectById(classifyId);
        if (null != classifyDO) {
            objectiveDetailCO.setClassifyName(classifyDO.getName());
            objectiveDetailCO.setClassifyId(classifyDO.getId());
        }

        if (objectiveDO == null) {
            throw new BusinessException("500", "没有查询到OKR内容");
        }
        //获取考核周期实体
        OkrPeriodDO okrPeriodDO = okrPeriodMapper.selectById(objectiveDO.getOkrPeriodId());
        OkrPeriodDetailCO okrPeriodDetailCO = okrPeriodClientConverter.dataToClient(okrPeriodDO);
        //判断当前登录用户所在部门是否关联周期
        //如果关联周期 则按照周期上的按钮管控权限
        //否则全部可以编辑
        QueryWrapper<PeriodControlDO> periodControlDOQueryWrapper = new QueryWrapper<>();
        periodControlDOQueryWrapper.eq("period_id", objectiveDO.getOkrPeriodId());
        PeriodControlDO periodControlDO = periodControlMapper.selectOne(periodControlDOQueryWrapper);
        OkrPeriodButtonCmd okrPeriodButtonCmd = new OkrPeriodButtonCmd();
        if (null != periodControlDO && !StringUtils.isEmpty(periodControlDO.getDeptId())) {
            List<Integer> list = JSON.parseObject(periodControlDO.getDeptId(), List.class);
            String userDept = getUserDept();
            if (list.contains(Integer.valueOf(userDept))) {
                String extInfo = okrPeriodDO.getExtInfo();
                if (!StringUtils.isEmpty(extInfo)) {
                    okrPeriodButtonCmd = JSON.parseObject(okrPeriodDO.getExtInfo(), OkrPeriodButtonCmd.class);
                    okrPeriodDetailCO.setOkrPeriodButtonCmd(okrPeriodButtonCmd);
                } else {
                    okrPeriodButtonCmd.setWeightSwitch(true);
                    okrPeriodButtonCmd.setScoreSwitch(true);
                    okrPeriodButtonCmd.setPlanSwitch(true);
                    okrPeriodButtonCmd.setObjectiveSwitch(true);
                    okrPeriodButtonCmd.setMySwitch(true);
                    okrPeriodButtonCmd.setLeaderSwitch(true);
                    okrPeriodButtonCmd.setKeyResultSwitch(true);
                    okrPeriodDetailCO.setOkrPeriodButtonCmd(okrPeriodButtonCmd);
                }
            } else {
                okrPeriodButtonCmd.setWeightSwitch(true);
                okrPeriodButtonCmd.setScoreSwitch(true);
                okrPeriodButtonCmd.setPlanSwitch(true);
                okrPeriodButtonCmd.setObjectiveSwitch(true);
                okrPeriodButtonCmd.setMySwitch(true);
                okrPeriodButtonCmd.setLeaderSwitch(true);
                okrPeriodButtonCmd.setKeyResultSwitch(true);
                okrPeriodDetailCO.setOkrPeriodButtonCmd(okrPeriodButtonCmd);
            }
        } else {
            okrPeriodButtonCmd.setWeightSwitch(true);
            okrPeriodButtonCmd.setScoreSwitch(true);
            okrPeriodButtonCmd.setPlanSwitch(true);
            okrPeriodButtonCmd.setObjectiveSwitch(true);
            okrPeriodButtonCmd.setMySwitch(true);
            okrPeriodButtonCmd.setLeaderSwitch(true);
            okrPeriodButtonCmd.setKeyResultSwitch(true);
            okrPeriodDetailCO.setOkrPeriodButtonCmd(okrPeriodButtonCmd);
        }
        //获取关键成果
        QueryWrapper<KeyResultDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", OkrConstants.NOT_DELETED);
        queryWrapper.eq("objective_id", objectiveId);
        queryWrapper.orderByAsc("show_sort");
        List<KeyResultDO> keyResultDOS = keyResultMapper.selectList(queryWrapper);
        List<KeyResultDetailCO> keyResultDetailCOS = keyResultClientConverter.dataToClients(keyResultDOS);

        //判断是否开启查看自我评价
        Byte myCommentEnable = okrPeriodDO.getMyCommentEnable();
        if (OkrConstants.NOT_DELETED.equals(myCommentEnable)) {
            //展示自我评价
            keyResultDetailCOS.forEach(x -> {
                QueryWrapper<KeyCommentDO> keyCommentDOQueryWrapper = new QueryWrapper<>();
                keyCommentDOQueryWrapper.eq("key_id", x.getId());
                keyCommentDOQueryWrapper.orderByDesc("create_time");
                KeyCommentDO keyCommentDO = keyCommentMapper.selectOne(keyCommentDOQueryWrapper);
                KeyCommentDetailCO keyCommentDetailCO = keyCommentClientConverter.dataToClient(keyCommentDO);
                x.setKeyCommentDetailCO(keyCommentDetailCO);
            });
        }

        //判断是否开启查看领导评价
        Byte leaderCommentEnable = okrPeriodDO.getLeaderCommentEnable();
        if (OkrConstants.NOT_DELETED.equals(leaderCommentEnable)) {
            //展示okr评论
            QueryWrapper<AllCommentDO> allCommentDOQueryWrapper = new QueryWrapper<>();
            allCommentDOQueryWrapper.eq("type", OkrConstants.DELETED);
            allCommentDOQueryWrapper.eq("okr_id", objectiveId);
            allCommentDOQueryWrapper.orderByDesc("create_time");
            AllCommentDO allCommentDO = allCommentMapper.selectOne(allCommentDOQueryWrapper);
            AllCommentDetailCO allCommentDetailCO = allCommentClientConverter.dataToClient(allCommentDO);
            objectiveDetailCO.setAllCommentDetailCOS(allCommentDetailCO);
        }
        //判断是否开启查看通用评价
        Byte allCommentEnable = okrPeriodDO.getAllCommentEnable();
        if (OkrConstants.NOT_DELETED.equals(allCommentEnable)) {
            //展示通用评价
            QueryWrapper<AllCommentDO> allCommentDOQueryWrapper = new QueryWrapper<>();
            allCommentDOQueryWrapper.eq("type", OkrConstants.NOT_DELETED);
            allCommentDOQueryWrapper.eq("okr_id", objectiveId);
            allCommentDOQueryWrapper.orderByDesc("create_time");
            List<AllCommentDO> allCommentDOS = allCommentMapper.selectList(allCommentDOQueryWrapper);
            List<AllCommentDetailCO> allCommentDetailCOS = allCommentClientConverter.dataToClients(allCommentDOS);
            okrDetailCO.setAllCommentDetailCOS(allCommentDetailCOS);
        }

        okrDetailCO.setObjectiveDetailCO(objectiveDetailCO);
        okrDetailCO.setOkrPeriodDetailCO(okrPeriodDetailCO);
        okrDetailCO.setKeyResultDetailCO(keyResultDetailCOS);
        return okrDetailCO;
    }

    /**
     * 查询用户当前周期下的所有okr
     *
     * @param cmd
     * @return
     */
    protected List<Integer> findUserOkrs(ListUserOKRCmd cmd) {
        QueryWrapper<ObjectiveDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", OkrConstants.NOT_DELETED);
        queryWrapper.eq("created", cmd.getUserId());
        queryWrapper.eq("okr_period_id", cmd.getOkrPeriodId());
        queryWrapper.orderByAsc("show_sort");
        List<ObjectiveDO> objectiveDOS = mapper.selectList(queryWrapper);
        return Optional.ofNullable(objectiveDOS).orElse(Arrays.asList())
                .stream()
                .map(ObjectiveDO::getId)
                .collect(Collectors.toList());
    }

    protected boolean deptLock(Integer userId, Integer periodId) {
        QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        UserDO userDO = userMapper.selectOne(queryWrapper);
        QueryWrapper<PeriodControlDO> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("period_id", periodId);
        List<PeriodControlDO> periodControlDOS = periodControlMapper.selectList(queryWrapper1);
        if (!CollectionUtils.isEmpty(periodControlDOS)) {
            for (int i = 0; i < periodControlDOS.size(); i++) {
                PeriodControlDO periodControlDO = periodControlDOS.get(i);
                if (!StringUtils.isEmpty(periodControlDO.getDeptId())) {
                    List<Integer> list = JSON.parseArray(periodControlDO.getDeptId(), Integer.class);
                    if (list.contains(Integer.valueOf(userDO.getDeptId()))) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    private String getUserDept() {
        QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", SessionUtils.currentUserId());
        UserDO userDO = userMapper.selectOne(queryWrapper);
        return userDO.getDeptId();
    }
}
